﻿package com.d4p.custom.imageLoader
{
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;

	public class ImageLoader extends Sprite
	{
		private var loader:Loader;
		private var urlRequest:URLRequest;
		
		public function ImageLoader()
		{
			super();
			
			this.loader = new Loader();
			this.addChild( loader );
		}
		public function load($url:String, $progress:Boolean):void
		{
			this.urlRequest = new URLRequest ( $url );
			
			this.loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
			if($progress) this.loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
			
			
			this.loader.load( this.urlRequest );
		}
		private function onProgress( e:ProgressEvent ):void
		{
			var byteLoad:uint = e.bytesLoaded;
			var byteTotal:uint = e.bytesTotal;
			
			this.dispatchEvent( new ImageProgressEvent( byteLoad, byteTotal, ImageProgressEvent.IMAGE_PROGRESS));
		}
		private function onComplete( e:Event ):void
		{
			/* var bitmapData:BitmapData = new BitmapData(loader.content.width, loader.content.height);
			bitmapData.draw(loader);
			
			var output:BitmapData = new BitmapData(100,100);
			var matrix:Matrix = new Matrix();
			matrix.scale(100/loader.content.width, 100/loader.content.height);
			
			output.draw( bitmapData, matrix, null, null, null, true);
			bitmapData.dispose();
			
			var bitmap:Bitmap = new Bitmap(output); */
			
			
			var bitmap:Bitmap 	= this.loader.content as Bitmap;
			//bitmap.smoothing 	= true;
			
			this.dispatchEvent( new ImageLoaderEvent( bitmap, ImageLoaderEvent.IMAGE_COMPLETE) );
		}
	}
}